<?php
namespace app\admin\middleware;
use auth\Action;
use app\admin\model\SystemNav;
use think\facade\View;

/**
* 权限校验中间件
* @package app\http\middleware
*/
class ChenkAction 
{	
	//自执行中间件方法
   	public function handle($request, \Closure $next){
        
		//判断当前用户的当前请求地址是否有权限
		if($request->userInfo){
			if( $request->userInfo['is_admin'] != 1 && $this-> userInfo["roles"] !=1  ){
				if(!$request->userAction = $this->is_exist_user_auth($request)){
					return \Api::ReError("无访问权限！", -2 );
				}
			}
			
			//判断当前用户的当前访问接口权限
			if($request->userInfo['is_admin'] != 1 && !$this->is_exist_action_auth($request)){
				return \Api::ReError("没有该操作的权限！", -2 );
			}
		}
		
        return $next($request);
    }
    
	/**
     * 验证用户访问权限
     * @return boolean
     */
    private function is_exist_user_auth($request){
    	$url = str_replace("views/","",$request->pathinfo());
        $url = $url ?: '/admgr/views/modules/index/index';
		$auths = SystemNav::getNavAuthCode($url);
		if($auths['func_code'] || $auths['func_code']=='0' || $auths['func_code']=='00'){
			return Action::instance($request->userInfo)->check( $auths['func_code'] ,'00' );
		}
		return true;
    }
	
	/**
     * 验证访问接口权限
     * @return boolean
     */
	private function is_exist_action_auth($request){
		$func_code = \base\other\Actions::getMethodDesc('func_code');
		$action_code =  \base\other\Actions::getMethodDesc('action_code');
		if( !empty($func_code)  && !empty($action_code) || $func_code== '0' || $action_code=='0'){
			return Action::instance($request->userInfo)->check( $func_code , $action_code );
		}
		return true;
	}

}